package com.ruge.test.springMVC.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 爱丽丝、如歌  创建于 2018/7/6 10:17
 * 说明:  TODO
 */
@Controller
public class LoginController {
    @RequestMapping(value = "login.do")
    //  @ResponseBody
    public String login(ShiroUser shiroUser) {
        Map<String, Object> map = new HashMap<>();
        /**
         * 获取当前的subject
         */
        Subject subject = SecurityUtils.getSubject();
        Boolean remember = false;
        UsernamePasswordToken token = new UsernamePasswordToken(shiroUser.getUserName(), shiroUser.getPassWord());

        if ("on".equals(shiroUser.getRemeberMe())) {
            remember = true;
        }
        token.setRememberMe(remember);

        try {
            subject.login(token);
            map.put("res", "登录成功");
            map.put("message", "success");
        } catch (Exception e) {
            map.put("res", "error");
            map.put("message", e.toString());
            e.printStackTrace();
        }
        return "/shiro/list";
    }

    @RequestMapping(value = "logout.do")
    public String layout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }


    @RequiresRoles("admin")
    @RequestMapping(value = "gotoAdmin.do")
    public String gotoList() {
        return "/shiro/admin";
    }

    @RequiresRoles("student")
    @RequestMapping(value = "gotoUser.do")
    public String gotoUser() {
        return "/shiro/user";
    }

}
